package bluetooth;
import lejos.pc.comm.*;

import java.io.*;

/**
 * Based on the source Lawrie Griffiths
 */
public class BTSend {
	
	private OutputStream dos;
	private InputStream dis;
	private NXTConnector conn;
	
	public void connect(){
		
		conn = new NXTConnector();

		conn.addLogListener(new NXTCommLogListener() {

			public void logEvent(String message) {
				System.out.println("BTSend Log.listener: " + message);

			}

			public void logEvent(Throwable throwable) {
				System.out.println("BTSend Log.listener - stack trace: ");
				throwable.printStackTrace();

			}

		});
		// Connect to any NXT over Bluetooth
		boolean connected = conn.connectTo("btspp://");

		if (!connected) {
			System.err.println("Failed to connect to any NXT");
			System.exit(1);
		}

		dos = conn.getOutputStream();
		dis = conn.getInputStream();
	}
	
	public void disconnect(){
		try {
			dis.close();
			dos.close();
			conn.close();
		} catch (IOException ioe) {
			System.out.println("IOException closing connection:");
			System.out.println(ioe.getMessage());
		}
	}
	
	public byte[] read(){
		try {
			byte[]rgb= new byte[3];
			System.out.println("Received " + dis.read(rgb));
			return rgb;
		} catch (IOException ioe) {
			System.out.println("IO Exception reading bytes:");
			System.out.println(ioe.getMessage());
		}
		return null;
	}
	
	public void write(byte[] rgbValues){
		try {
			System.out.println("Sending " + rgbValues);
			dos.write(rgbValues);
			dos.flush();

		} catch (IOException ioe) {
			System.out.println("IO Exception writing bytes:");
			System.out.println(ioe.getMessage());
		}
	}
}
